<template>
	<!--index.wxml-->

	<view class="container">
		<view class="swiper-box">
			<view class="nickname-box">
				<view class="nickname">{{userInfo ? userInfo.nickname : ''}}!你好</view>
			</view>
			<image src="/static/images/bg@2x.png" class="backimg"></image>

			<swiper class="swiper" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
				:duration="duration">
				<block v-for="(item, index) in background" :key="index">
					<swiper-item>
						<image class="img" :src="item.adv_img"></image>
					</swiper-item>
				</block>
			</swiper>

		</view>
		<view class="progress-item">
			<view>您目前还可以预支付{{num-ordernum}}次</view>
			<i-progress :percent="percent" :status="status"></i-progress>
		</view>

		<view class="btn-box">
			<view v-if="device==''">未定位到设备</view>
			<view v-else>
				<view>当前设备：{{device.address}}。</view>
				<view>设备编号：{{device.device_num}}</view>
			</view>
			<button style="width: 320px;" class="btn" v-if="login_check==0" @tap="openPopup">授权登录</button>
			<!-- <button style="width: 320px;" class="btn" @tap="payAli">支付</button> -->
			<!-- <button style="width: 320px;" class="btn" v-if="login_check==0" open-type="getUserInfo" @getuserinfo="bindGetUserInfo">授权登录</button> -->
			<button style="width: 320px;" class="btn" v-if="login_check==1" @tap="get_paper">立即出纸</button>
		</view>

		<!-- 登录弹窗 -->
		<ns-login ref="login" @loginSuccess="loginSuccess"></ns-login>
		<uni-popup ref="auth" :custom="true" :mask-click="false">
			<view class="uni-tip">
				<rich-text :nodes="content"></rich-text>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import uniPopup from '../../components/uni-popup/uni-popup.vue';
	//index.js
	const app = getApp().globalData;
	const {
		$Message
	} = require("../../dist/base/index");
	var sotk = null;
	var socketOpen = false;
	// var wsbasePath = "ws://39.105.123.96:39100";
	var wsbasePath = "wss://yhz.axu9.com/wss";
	import iTabBar from "../../dist/tab-bar/index";
	import iTabBarItem from "../../dist/tab-bar-item/index";
	import iProgress from "../../dist/progress/index";
	import iButton from "../../dist/button/index";
	import iModal from "../../dist/modal/index";
	import nsLogin from "../../components/ns-login/ns-login.vue"
	import auth from 'common/js/auth.js';
	import {
		getBanner,
		getDevice,
		aligetToken,
		selectOrder,
		unifiedOrder,
		aliPay,
		arrayToBase64
	} from '@/api/setting.js'

	export default {
		data() {
			return {
				background: ["/static/images/agent_img01599810087.jpeg", "/static/images/idimg01599807828.jpeg",
					"/static/images/idimg11599810002.jpeg"
				],
				indicatorDots: true,
				vertical: false,
				autoplay: true,
				interval: 2000,
				duration: 500,
				percent: 0,
				status: 'normal',
				canIUse: uni.canIUse('button.open-type.getUserInfo'),
				login_check: 0,
				device: "",
				user: "",
				num: "",
				price: "",
				ordernum: "",
				orderlist: "",
				userInfo: {},
				photo: '',
				user_id: '',
				orderInfo: {
					orderld: 11111333444,
					totalFee: 1,
					subject: '商品',
					outTradeNo: 3211234242444,

					// mch_id: '',
					// package: '',
					// timestamp: '',
					// nonce_str: '',
					// sign_type: 'sign_type',
					// sign: '',
					// id: ''
				},
				content: ''
				// nickName: ''
			};
		},

		components: {
			iTabBar,
			iTabBarItem,
			iProgress,
			iButton,
			iModal,
			nsLogin,
			uniPopup
		},
		watch: {

			nickName(newValue, oldValue) {
				console.log(newValue, 'watch')
			}
		},
		props: {},
		onShow() {
			var _this = this;
			_this.userInfo = uni.getStorageSync('userInfo')
			// _this.nickName = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').nickname : ''
			_this.login_check = uni.getStorageSync('login_check')
			// _this.photo = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').photo : ''
			console.log(_this.nickName, '_this.nickName')
			_this.user_id = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').user_id : ''
			if (_this.user_id) {
				_this.getorder(_this.user_id);
			}


		},
		onLoad: function(query) {
			console.log(query, 'query')
			console.log(app.post_url, 'app.post_url')
			// this.getbanner();
			// uni.request({
			// 	url: 'https://shops.cg500.com/addons/yun_shop/api.php?i=8&type=2&route=Gongxiao.jiagou',
			// 	//仅为示例，并非真实的接口地址
			// 	data: {
			// 		uid:19773,
			// 		goods_id: ''
			// 	},
			// 	method: 'post',

			// 	success(res) {
			// 		console.log(res, '获取订单信息');

			// 		// _this.setData({
			// 		// 	ordernum: res.data.data.data.length,
			// 		// 	orderlist: res.data.data.data,
			// 		// 	percent: res.data.data.data.length * 20
			// 		// });
			// 	}

			// });
			var _this = this;
			// _this.userInfo = uni.getStorageSync('userInfo')
			// _this.login_check = uni.getStorageSync('login_check')
			// const scene = decodeURIComponent(query.scene);
			const scene = query.device_only;
			console.log(scene, 'scene')
			if (scene === 'undefined') {
				console.log('没有设备号')
				this.setData({
					device: ''
				});
				// this.getorder(this.user_id);
			} else {
				console.log(scene);
				this.get_device(scene);
				// this.getorder(this.user_id);
			} // 登录
			console.log(this.$refs.login, 'login')
			// this.$refs.login.open('/otherpages/recharge/order_list/order_list');
			// uni.login({
			//   success: res => {
			//     // 发送 res.code 到后台换取 openId, sessionKey, unionId
			//     this.getopenid(res.code);
			//   }
			// });
			this.getbanner();
		},
		methods: {
			payAli() {
				// aliPay().then(res => {
				// 	console.log(res,'阿里支付')
				// })
				let _this = this;
				// uni.request({    
				// 	url: 'https://yhz.axu9.com/api/wechat/alipay', //接口地址：前缀+方法中传入的地址
				// 	method: "POST", //请求方法：传入的方法或者默认是“GET”    
				// 	data: {}, //传递参数：传入的参数或者默认传递空集合    
				// 	dataType: 'text',
				// 	header: {},     
				// 	success: (res) => {     //返回的数据（不固定，看后端接口，这里是做了一个判断，如果不为true，用uni.showToast方法提示获取数据失败)     // 如果不满足上述判断就输出数据     
				// 		console.log(res)
				// 		let aa = res.data
				// 		let jsonString = aa.replace(/﻿/g, '');
				// 		let data = JSON.parse(jsonString)
				// 		console.log(data.data, '阿里支付');
				// 		_this.content = data.data 
				// 		_this.$refs.auth.open();
				// 		// if (data.code == 1 || data.code == 0 || data.code == 200) {      
				// 		// 	resolve(data)
				// 		// } else {   
				// 		// 	 reject(data);
				// 		// }    
				// 	},
				// })
				my.tradePay({
					// provider: "alipay", // wxpay、alipay
					// orderInfo: this.orderInfo, //微信、支付宝订单数据
					orderStr: 'alipay_sdk=alipay-sdk-php-20200415&app_id=2021004113627220&biz_content=%7B%22body%22%3A%22xxx%22%2C%22subject%22%3A%22%E6%A0%87%E9%A2%98%22%2C%22out_trade_no%22%3A%2216950150821574%22%2C%22total_amount%22%3A1%7D&charset=utf-8&format=json&method=alipay.trade.wap.pay&sign_type=RSA2×tamp=2023-09-18+13%3A31%3A22&version=1.0&sign=Of%2B48XdITSjQds7Y403%2FBSCHqmxjMYPJliG4VJW0c9WgRTs%2BvcfDn2sCOz4aKTYp4%2FRqthtFsXTpVOqDzMbUPV2Q2bL9HFjxvagxMCTmRrIupZIAx9JZRk%2Ba6qXYjl%2BTrLta9O2kpmG4eAKX7avF0r%2FnW5xvRL0hPCa%2F%2B12eQpwv2v6COzJ5AqI6Kp2glte4g73plhJx16LTkTDe5jUL2HgWUEdNHetHsu0Td5ZuxIT1yQI%2BbVyLyLujrFzHcIaTBq9kno%2FaWhRUF28Dd%2FIDaSLHvTXJUy04dAvQ5OFabRlJM2qn9b3%2Ft3c3zS6h3Ek6%2BqYCPzUxdniVg2jEjgfQsg%3D%3D',
					success: function(res) {
						console.log('success:', res);
						// aliPay().then(res => {
						// 	console.log(res,'阿里支付')
						// })
					},
					fail: function(err) {
						console.log('fail:', err);
					}
				});
			},
			getAuthCode() {
				let _this = this
				my.getAuthCode({
					scopes: 'auth_user',
					success: res => {
						console.log(res, 'resdsssssss')
						const authCode = res.authCode;
						console.log(authCode, 'authCode')
						aligetToken({
							code: authCode
						}).then(res => {
							console.log(res, 'aligetToken')
							let openId = res.open_id
							let accessToken = res.access_token
							uni.setStorageSync('openId', openId)
							uni.setStorageSync('accessToken', accessToken)
							_this.$refs.login.open()
						})

					},
					fail: err => {
						console.log('my.getAuthCode 调用失败', err)
					}
				});
			},
			onChooseAvatar() {
				console.log('qqqqqq')
				uni.chooseImage({
					count: 6,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: function(res) {
						// 预览图片
						let _this = this
						console.log(res, 'res')
						// const { avatarUrl } = e.detail 
						// this.setData({
						//   avatarUrl,
						// })
						let avatarUrl = res.tempFilePaths[0]
						// console.log(_this.avatarUrl, '_this.avatarUrl')

						uni.uploadFile({
							url: 'https://yhzzf.axu9.com/api/v1.order/file',
							filePath: avatarUrl,
							name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
							header: {
								// "Authorization": uni.getStorageSync('token')
							},
							success: (res) => {
								// let infoObj = JSON.parse(res.data)
								console.log(JSON.parse(res.data), '成功')
								// _this.avatar_url = infoObj.data.img
								// console.log(_this.avatar_url, '_this.avatar_url')
							},
							fail: (err) => {
								console.log(err, '失败')
							}
						})
					}
				});


			},
			loginSuccess() {
				console.log('11111')
				this.userInfo = uni.getStorageSync('userInfo')
				this.user_id = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').user_id : ''
				this.login_check = uni.getStorageSync('login_check')
				this.getorder(this.user_id);
				// this.photo = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').photo : ''

			},
			openPopup() {
				// #ifdef MP-WEIXIN
				this.$refs.login.open()
				// #endif
				// #ifdef MP-ALIPAY
				console.log('支付宝环境')
				// this.$refs.login.open()
				this.getAuthCode()
				// this.$refs.login.open()
				// #endif

			},
			bindGetUserInfo(e) {
				var data = {
					nickname: e.detail.userInfo.nickName,
					photo: e.detail.userInfo.avatarUrl,
					openid: app.openid,
					sex: e.detail.userInfo.gender
				};
				this.reguser(data);
				console.log(e.detail.userInfo);
				console.log(app.openid);
			},

			//获取轮播图及预支付次数
			getbanner: function() {
				var _this = this;
				getBanner().then(res => {
					console.log(res, 'getBanner')
					if (res.code == 1) {
						_this.background = res.data.list
						_this.num = res.data.num
						_this.price = res.data.price
					}
				})
			},
			//获取设备信息
			get_device: function(num) {
				var _this = this;
				getDevice({
					device_only: num
				}).then(res => {
					console.log(res, 'rrr')
					if(res.data.state == 0){
						uni.showToast({
							title: '设备维护中',
							icon: 'error'
						})
						return
					}
					_this.device = res.data

					_this.webSocketStart();
				})

			},

			handleAdd() {
				if (this.percent === 100) return;
				this.setData({
					percent: this.percent + 100 / this.num
				});

				if (this.percent === 100) {
					this.setData({
						status: 'success'
					});
				}
			},

			handleReduce() {
				if (this.percent === 0) return;
				this.setData({
					percent: this.percent - 20,
					status: 'normal'
				});
			},

			handleChange({
				detail
			}) {
				console.log(detail);
			},

			//获取订单信息
			getorder: function(user_id) {
				var _this = this;
				selectOrder({
					user_id: _this.user_id,
					status: 0
				}).then(res => {
					console.log(res, '获取订单信息');
					_this.ordernum = res.data.data.length
					_this.orderlist = res.data.data
					_this.percent = res.data.data.length * 20
				})
			},
			get_paper: function() {
				var _this = this;

				console.log(this.device);
				if (!this.device) {
					wx.showToast({
						title: '未找到设备',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				console.log(this.percent, 'this.percent')
				if (this.percent >= 100) {
					uni.showModal({
						title: '需要支付' + this.num * this.price + '元',
						content: '目前已使用' + this.num + '次，结清可再次使用',
						showCancel: false,
						// confirmColor: '#459377',
						success(res) {
							if (res.confirm) {
								_this.pay_all()
							}
						}

					});
				} else {

					let data = {
						total_price: this.price,
						user_id: this.user_id,
						device_id: this.device.device_id,
						address: this.device.address
					};
					console.log(1);

					if (socketOpen) {
						console.log(this.device.device_num, 'device.device_num')

						// this.sendSocketMessage({
						// 	device_num: _this.device.device_num,
						// 	msg: 'aa552020120100201'
						// });
						// hahahahaha
						this.sendSocketMessage({
							id: _this.device.device_num,
							command: 'aa552021081900201\r\n'
						});
					} else {
						_this.webSocketReStart();
					} 
					// this.add_order(data)

				}
			},
			
			pay_all: function() {
				var _this = this;
				console.log(app, 'app1')
				let user_id = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').user_id : ''
				aliPay({
					user_id: user_id,
					status: 0
				}).then(res => {
					console.log(res,'aliPay')
					console.log(12312312,res.data.alipay_trade_create_response.trade_no);
					let trade_no = res.data.alipay_trade_create_response.trade_no
					uni.getProvider({
						service: 'payment',
						success: function(res) {
							console.log(res, 'getProvider')
							if (~res.provider.indexOf('alipay')) {
								// 支付宝支付功能可用
								// 进行支付请求
								uni.requestPayment({
									provider: 'alipay',
									orderInfo: trade_no,
									success: function(res) {
										console.log('支付成功');
									},
									fail: function(err) {
										console.log('支付失败', err);
									}
								})
							}
						},
						fail: function(err) {
							console.log('暂不支持支付宝支付');
						}
					})
					
				})
				
				// uni.request({
				// 	url: 'https://yhzzf.axu9.com/api/v1.order/pay',
				// 	//仅为示例，并非真实的接口地址
				// 	data: {
				// 		user_id: user_id,
				// 		status: 0
				// 	},
				// 	method: 'post',

				// 	success(res) {
				// 		console.log(res);
				// 		uni.requestPayment({
				// 			timeStamp: res.data.data.payInfo.timeStamp,
				// 			nonceStr: res.data.data.payInfo.nonceStr,
				// 			package: res.data.data.payInfo.package,
				// 			signType: 'MD5',
				// 			paySign: res.data.data.payInfo.paySign,

				// 			success(res) {},

				// 			fail(res) {}

				// 		});
				// 	}
				// });
			},
			add_order: function(data) {
				
				uni.showLoading({
					title: '加载中'
				});

				var _this = this;
				unifiedOrder(data).then(res => {
					console.log('unifiedOrderunifiedOrder')
					_this.getorder(_this.user_id);
					uni.hideLoading();
				})
				
			},
			reguser: function(data) {
				var _this = this;

				uni.request({
					url: app.post_url + '/api/v1/userReg',
					//仅为示例，并非真实的接口地址
					data: data,
					method: 'post',

					success(res) {
						console.log(res);

						_this.setData({
							login_check: 1
						});

						getApp().user_info = res.data.data;

						_this.setData({
							user: app.user_info
						});
					}

				});
			},
			//重新连接---------------------------------------------------------------
			webSocketReStart: function(e) {
				var _this = this;
				sotk = my.connectSocket({
					url: wsbasePath,
					multiple: true,
					success: (res) => {
						console.log('走了么url: ' + res)
					},
					fail: (res) => {
						console.log('走了么fail：' + JSON.stringify(res))
					}
				});
				// my.connectSocket({
				// 	url: wsbasePath,
				// 	success: (res) => {
				// 		console.log('connect url: ' + wsbasePath)
				// 	},
				// 	fail: (res) => {
				// 		console.log('connect fail：' + JSON.stringify(res))
				// 	}
				// })
				this.webSokcketReMethods();
			},
			//重新
			webSokcketReMethods: function(e) {
				let that = this;
				sotk.onOpen(res => {
					socketOpen = true;
					console.log('走了么open', res);
					console.log(that.device.device_num, 'this.device.device_num')
					// that.sendSocketMessage({
					// 	device_num: that.device.device_num,
					// 	msg: 'aa552020120100201'
					// });
					that.sendSocketMessage({
						id: that.device.device_num,
						command: 'aa552021081900201\r\n'
					});
				});
				sotk.onClose(onClose => {
					console.log('监听 WebSocket 连接关闭事件。', onClose);
					socketOpen = false;
				});
				sotk.onError(onError => {
					console.log('监听 WebSocket 错误。错误信息', onError);
					socketOpen = false;
				});
				sotk.onMessage(onMessage => {
					console.log(onMessage.data);
					var data = JSON.parse(onMessage.data.data);
					if(data.code == 1){
						let data = {
							total_price: this.price,
							user_id: this.user_id,
							device_id: this.device.device_id,
							address: this.device.address
						};
						this.add_order(data)
					}
					console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息',data);
					that.closeWebsocket(onMessage.data); 
					
				});
				
				
				
				
				// my.onSocketOpen(function(res) {
				// 	socketOpen = true;
				// 	console.log('监听 WebSocket 连接打开事件。', res);
				// 	console.log(that.device.device_num, 'this.device.device_num')
				// 	// that.sendSocketMessage({
				// 	// 	device_num: that.device.device_num,
				// 	// 	msg: 'aa552020120100201'
				// 	// });
				// 	that.sendSocketMessage({
				// 		id: that.device.device_num,
				// 		command: 'aa552021081900201\r\n'
				// 	});
				// })
				// //被动关闭 socket 的回调
				// my.onSocketClose(function(onClose) {
				// 	console.log('监听 WebSocket 连接关闭事件。', onClose);
				// 	socketOpen = false;
				// })
				// //打开 socket错误回调！
				// my.onSocketError(function(onError) {
				// 	console.log('监听 WebSocket 错误。错误信息', onError);
				// 	socketOpen = false;
				// })
				// //监听到socket的数据下发回调
				// my.onSocketMessage((onMessage) => {
				// 	//这里主要是对数据的判断，因为有时候是字符串，有时候是数组！
				// 	console.log(onMessage.data, '3333333333333');
				// 	that.closeWebsocket(onMessage.data); //var data = JSON.parse(onMessage.data);
				// });


			},
			//开始webSocket---------------------------------------------------------------
			webSocketStart: function(e) {
				var _this = this;
				console.log('走了么')
				sotk = my.connectSocket({
					url: wsbasePath,
					multiple: true,
					success: (res) => {
						console.log('走了么url: ' + res)
					},
					fail: (res) => {
						console.log('走了么fail：' + JSON.stringify(res))
					}
				});
				
				this.webSokcketMethods();
			},
			//监听指令
			webSokcketMethods: function(e) {
				let that = this;
				console.log(sotk, 'sotksotksotk')
				// 打开 socket

				sotk.onOpen(res => {
					socketOpen = true;
					console.log('走了么open', res);
					console.log(that.device.device_num, 'this.device.device_num')
					// that.sendSocketMessage({
					// 	device_num: that.device.device_num,
					// 	msg: 'aa552020120100201'
					// });
					// that.sendSocketMessage({
					// 	id: that.device.device_num,
					// 	command: 'aa552021081900201\r\n'
					// });
				});
				sotk.onClose(onClose => {
					console.log('监听 WebSocket 连接关闭事件。', onClose);
					socketOpen = false;
				});
				sotk.onError(onError => {
					console.log('监听 WebSocket 错误。错误信息', onError);
					socketOpen = false;
				});
				sotk.onMessage(onMessage => {
					console.log(onMessage.data);
					var data = JSON.parse(onMessage.data.data);
					console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息1',data);
					if(data.code == 1){
						let data = {
							total_price: this.price,
							user_id: this.user_id,
							device_id: this.device.device_id,
							address: this.device.address
						};
						this.add_order(data)
					}
					
					that.closeWebsocket(onMessage.data); 
					
				});
			},
			//发送消息
			sendSocketMessage: function(msg) {
				console.log(11);
				let that = this;

				if (socketOpen) {
					console.log('通过 WebSocket 连接发送数据1', JSON.stringify(msg));
					
					sotk.send({
						data: JSON.stringify(msg)
					}, function(res) {
						console.log('已发送', res);
						
					});

				}
			},
			//关闭连接
			closeWebsocket: function(str) {
				if (socketOpen) {
					sotk.close({
						code: "1000",
						reason: str,
						success: function() {
							console.log("成功关闭websocket连接1");
						}
					});
				}
			}
		}
	};
</script>
<style>
	@import "./index.css";

	.headimg {
		width: 70px;
		height: 70px;
		border-radius: 20px;
		margin-right: 15px;
		box-shadow: 1px 2px 14px #000;
	}

	.uni-tip {
		width: 580rpx;
		background: #fff;
		box-sizing: border-box;
		border-radius: 10rpx;
		overflow: hidden;
		height: initial;
	}
</style>